package com.juc.future;

import java.util.concurrent.*;

/**
 * @Author HK
 * @Date 2022/5/14 15:54
 * @Version 1.0
 */
public class FutureTaskDemo {


    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {

        FutureTask<Integer> vFutureTask = new FutureTask<Integer>(() -> {
            System.out.println(Thread.currentThread().getName()+",is come on!");
            //假设这段业务代码要执行5s
            TimeUnit.SECONDS.sleep(5);
            return 1;
        });
        new Thread(vFutureTask).start();

        //System.out.println(vFutureTask.get()); //遇到get就会导致阻塞了
        //System.out.println(vFutureTask.get(2L, TimeUnit.SECONDS)); //超时不候，会报错


        //不要用阻塞，尽量用轮询替代 ->但会耗费系统资源，还阻塞了主线程的执行
        while (true){
            if (vFutureTask.isDone()){
                System.out.println("result:"+ vFutureTask.get());
                break;
            }else {
                System.out.println("还在计算中....");
            }
        }


        System.out.println("不要阻塞我，因为我是主线程，不能停止！！");
    }

}
